package com.pizza.database.mapping;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.pizza.database.DBConnection;
import com.pizza.model.*;

/**
 * Class RemiseDB, mapping avec la bdd. Non utilisé.
 *
 */
public class RemiseDB implements Serializable {

	private DBConnection dbConnexion;

	public RemiseDB(DBConnection _dbConnexion)
	{
		dbConnexion = _dbConnexion;
	}

	public int insertRemise(Remise _remise)
	{
		int retour = 0;

		Connection connexion = dbConnexion.getConnection();
		StringBuilder query = new StringBuilder();
		query.append("INSERT INTO remises");
		query
				.append(" (montant, codepromo, description)");
		query.append(" VALUES(?,?,?)");

		try
		{
			PreparedStatement pStatement = connexion.prepareStatement(query.toString());

			pStatement.setFloat(1, _remise.getMontant());
			pStatement.setString(2, _remise.getCodepromo());
			pStatement.setString(3, _remise.getDescription());
			
			// Insertion de la remise
			retour += pStatement.executeUpdate();

			ResultSet rs = pStatement.getGeneratedKeys();
			rs.first();
			_remise.setId(rs.getInt(1));
			rs.close();

			pStatement.close();

		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		return retour;
	}

	public Remise getRemiseById(int _id)
	{
		Connection connexion = dbConnexion.getConnection();
		Remise retour = null;
		StringBuilder query = new StringBuilder();
		query
				.append("SELECT * ");
		query.append(" FROM remises");
		query.append(" WHERE id=?");
		try
		{
			PreparedStatement pStatement = connexion.prepareStatement(query.toString());
			pStatement.setInt(1, _id);
			ResultSet rs = pStatement.executeQuery();
			rs.first();

			float montant = rs.getFloat("montant");
			String codepromo = rs.getString("codepromo");
			String description = rs.getString("description");
			
			retour = new Remise(_id, montant, codepromo, description);
			
			pStatement.close();
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		return retour;
	}

}
